package com.chat.server.base;

import com.alibaba.fastjson.JSON;
import com.chat.zookeeper.ZkUtil;
import io.netty.util.internal.StringUtil;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther created by haoteng on 2019/08/20
 */
public class ServiceRegister {
    /**
     * 注册服务
     *
     * @param packageName 完整包名 （com.user.base）
     * @param data        包含服务ip,port等
     */
    public Boolean register(String packageName, Object data) {
        String fullPath = packageName;
        String[] pathList = fullPath.split("\\$");
        ZkUtil zkUtil = new ZkUtil();
        String path = "";
        for (int i = 0; i < pathList.length; i++) {
            path = path + "/" + pathList[i];
            if (!zkUtil.exists(path) && i < pathList.length - 1) {
                zkUtil.create(path, "", CreateMode.PERSISTENT);
            }
            if (i == pathList.length - 1) {
                zkUtil.create(path, JSON.toJSONString(data), CreateMode.EPHEMERAL);
                return true;
            }
        }
        return false;
    }

    public List<MetadataUnit> getAllZkMetadata(String packageName) {
        String[] pathList = packageName.split("\\$");
        String path = "";
        for (int i = 0; i < pathList.length; i++) {
            path = path + "/" + pathList[i];
        }
        ZkUtil zkUtil = new ZkUtil();
        List<String> childrenList = zkUtil.getChildren(path, new RegisterWatcher());
        if (!childrenList.isEmpty()) {
            List<MetadataUnit> list = new ArrayList<>();
            for (String child : childrenList) {
                String data = zkUtil.getData(path + "/" + child);
                if (!StringUtil.isNullOrEmpty(data)) {
                    MetadataUnit metadataUnit = JSON.parseObject(data, MetadataUnit.class);
                    list.add(metadataUnit);
                }
            }
            return list;
        } else {
            return new ArrayList<>();
        }
    }

    private static class RegisterWatcher implements Watcher {
        @Override
        public void process(WatchedEvent watchedEvent) {
            System.out.println("1111连接通知:" + watchedEvent.toString());

        }
    }

}

